Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
Hoisting of "var" in javascript

I have read the following

Hoisting of var

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:

console.log (greeter);
var greeter = "say hello"

it is interpreted as this:

var greeter;
console.log(greeter); // greeter is undefined
greeter = "say hello"

So var variables are hoisted to the top of their scope and initialized with a value of undefined.

But what happens with this (undefined) They move at the top then why it is "undefined"?

if (true) {
  console.log(hi)
}
var hi = 1

If they are pushed up, they would also have to be "read" first, wouldn't they?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Javascript only hoists declarations. The initialization is not hoisted.. The assignment only happens after your if condition.

This is also why some JS developers prefer let over var. If you use let, you will get a very clear error saying the variable cannot be

if (true) {
  console.log(hi);
}
let hi = 1;
//Uncaught ReferenceError: Cannot access 'hi' before initialization
about 4 years ago · Juan Pablo Isaza Relatório

0

The declaration is hoisted, but the assignment isn't.

It's really the same as the second example in your quote. So it's the equivalent of:

var hi;
if (true) {
  console.log(hi)
}
hi = 1

So hi is still undefined at the log statement.

This article has some good discussion and examples: https://blog.logrocket.com/demystifying-function-and-variable-hoisting-in-javascript/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda